/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-06-29 21:59:50
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-09-11 22:26:50
 * @description: 
 */ 
import React, { useEffect, useState } from 'react'
import {
  FlatList,
  SafeAreaView,
} from 'react-native'
import { useDispatch } from 'react-redux'
import NewsItem from '@/components/NewsItem'
import EmptyList from '@/components/EmptyList'

import styles from './styles'
import * as userActions from '@/actions/user'

const Collection = props => {
  const dispatch = useDispatch()
  const [collectionList, setCollectionList] = useState([])
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [pageNum, setPageNum] = useState(1)
  const [pageEnd, setPageEnd] = useState(false)
  const pageSize = 20

  useEffect(() => {
    dispatch(userActions.getCollection(pageNum, pageSize)).then(res => {
      setIsRefreshing(false)
      if (pageNum === 1) {
        setCollectionList(res.list)
      } else {
        setCollectionList(collectionList.concat(res.list))
      }
      setPageEnd(res.total <= (res.pageNum * res.pageSize))
    })
  }, [pageNum, pageSize])

  const _renderItem = ({ item }) => (
    <NewsItem id={item.collId} title={item.title} coverImgs={item.coverUrl} type={item.artType} topping={item.topping} />
  )

  // 刷新
  const _onRefresh = () => {
    setPageNum(1)
    setIsRefreshing(true)
  }

  // 加载更多
  const _onLoadMore = () => {
    if (pageEnd) return
    setPageNum(pageNum + 1)
  }

  return (
    <>
      <SafeAreaView style={styles.wrap}>
        <FlatList
          data={collectionList}
          renderItem={_renderItem}
          onRefresh={_onRefresh}
          refreshing={isRefreshing}
          onEndReached={_onLoadMore}
          keyExtractor={item => item.id + item.title}
          ListEmptyComponent={<EmptyList />}
        />
      </SafeAreaView>
    </>
  )
}

export default Collection